<template>
  <div class="upload-file">
    <a-upload
      v-bind="attrs"
      v-model:fileList="fileList"
      name="file"
      :multiple="multiple"
      :customRequest="uploadRequest"
      :before-upload="beforeUpload"
      @preview="handlePreview"
      @remove="removeFileHandle"
    >
      <slot v-if="fileList.length < maxCount">
        <a-button>
          <upload-outlined></upload-outlined>
          {{ btnText }}
        </a-button>
      </slot>
    </a-upload>
    <!-- 是否支持粘贴 -->
    <div v-if="canPast" class="past-wrapper">
      <div class="past-contener" contenteditable :id="pastId"></div>
      <div class="past-tip">
        <div><i class="el-icon-document-copy"></i></div>
        粘贴图片上传
      </div>
    </div>
    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="图片预览" style="width: 100%" :src="previewImage" />
    </a-modal>

    <div style="display: none">
      <a-image-preview-group :preview="{ visible:showVisible, onVisibleChange: (vis:boolean) => (showVisible = vis) }">
        <a-image :src="item.url" v-for="(item, index) in fileList" :key="index" />
      </a-image-preview-group>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: "CustomerUploadFile"
};
</script>
<script lang="ts" setup>
import { message, Upload, Modal } from "ant-design-vue";
import { createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import type { UploadProps } from "ant-design-vue";
import { onMounted, ref, toRefs, useAttrs, watch } from "vue";
import { uploadApi } from "@/api/common/index";
import InitHook from "./composables/initHook";
const props = withDefaults(
  defineProps<{
    canPast?: boolean;
    maxCount?: number;
    btnText?: string;
    multiple?: boolean;
    mode: string;
    valueType?: string;
    value: Array<Base.GeneraDataType>;
  }>(),
  {
    btnText: () => "上传",
    valueType: "1", // '1' 返回纯链接    '2' 返回文件对象
    multiple: true,
    mode: "parent",
    maxCount: 999,
    canPast: false
  }
);
const emit = defineEmits<{
  (e: "update:value", fileList: Array<Base.GeneraDataType>): void;
}>();
const attrs = useAttrs();
const { btnText, multiple, mode, value, maxCount, valueType, canPast } = toRefs(props);
const pastId = ref<string>(Date.now().toString());
const fileList = ref<Array<Base.GeneraDataType>>([]);
const previewVisible = ref<boolean>(false);
const previewImage = ref<string>("");
const previewTitle = ref<string>("");
const showVisible = ref<boolean>(false);
const { initPastImg } = InitHook({ maxCount, pastId, fileList, mode, valueType, value, emit });
const uploadRequest = (e: any) => {
  if (fileList.value.length > maxCount.value) {
    init();
    return message.error(`最多上传${maxCount.value}张图片!`);
  }
  const fromData = new FormData();
  fromData.append("file", e.file);
  return uploadApi({ path: mode.value }, fromData).then((res: any) => {
    let result: Base.GeneraDataType[] = [];
    if (valueType.value === "2") result = value.value.concat(res.data);
    else result = value.value.concat(res.data.url);
    emit("update:value", result);
    e.onProgress({ percent: 100 });
  });
};
const beforeUpload: UploadProps["beforeUpload"] = file => {
  const imageType = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
  const size = file.size / 1024 / 1024 > 500;
  return new Promise((resolve, reject) => {
    if (size) {
      message.error("文件大小不能超过500M!");
      return !size || Upload.LIST_IGNORE;
    }
    if (!imageType) {
      message.error("只能上传PNG、JPG文件、JPEG、GIF!");
      return !imageType || Upload.LIST_IGNORE;
    }
    resolve();
  });
};
const handlePreview = async (file: any) => {
  showVisible.value = true;
  // previewImage.value = file.thumbUrl || file.response.data.url;
  // previewVisible.value = true;
  // previewTitle.value = file.name || file.response.data.url.substring(file.response.data.url.lastIndexOf("/") + 1);
};
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = "";
};
const removeFileHandle = (e: any) => {
  let result: any;
  if (valueType.value === "1") {
    result = value.value.filter((t: any) => t !== e.url);
  } else {
    result = value.value.filter((t: any) => t.url !== e.url);
  }
  console.log(fileList.value);

  Modal.confirm({
    title: "是否删除？",
    icon: createVNode(ExclamationCircleOutlined),
    content: "",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk() {
      emit("update:value", result);
    }
  });
  return false;
};
const init = () => {
  if (valueType.value === "1") {
    fileList.value = value.value.map((t: any) => {
      return {
        uid: `${t}`,
        name: `${t.split("/")[t.split("/").length - 1]}`,
        status: "done",
        url: t,
        thumbUrl: t
      };
    });
  } else {
    fileList.value = value.value.map((t: any) => {
      return {
        uid: `${t.url}`,
        name: `${t.originalFilename}`,
        status: "done",
        url: t.url,
        thumbUrl: t.url
      };
    });
  }
};
watch(
  () => value.value,
  () => {
    init();
  }
);
init();
onMounted(() => {
  if (canPast.value) {
    initPastImg();
  }
});
</script>
<style lang="stylus" scoped>
.past-wrapper {
    position: relative;
    width: 150px;
    cursor: pointer;
    .past-contener {
        border: 1px dashed #ccc;
        cursor: pointer;
        border-radius: 5px;
        height: 150px;
        width: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .past-tip {
        position: absolute;
        color: #ccc;
        font-weight: 600;
        text-align: center;
        top: 50%;
        transform: translate3d(-50%, -50%, 0);
        left: 50%;
        width: 100%;
    }
}
</style>
